/**
 * 全局主题状态管理
 * @description 管理应用的主题状态和切换逻辑
 */

import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { THEME_CONFIGS, DEFAULT_THEME, THEME_STORAGE_KEY, type ThemeKey, type ThemeConfig } from '@/config/theme.config'
import { useSimpleStorage } from '@/hooks/useStore'

// 获取store名称前缀
const getPrefixName = (name: string) => `uniapp_base_${name}`

export const useThemeStore = defineStore(getPrefixName('theme'), () => {
    // 持久化存储当前主题
    const { value: currentTheme, setValue: setCurrentTheme } = useSimpleStorage<ThemeKey>(THEME_STORAGE_KEY, DEFAULT_THEME)

    // 主题切换动画状态
    const isTransitioning = ref(false)

    // 计算属性：当前主题配置
    const currentThemeConfig = computed<ThemeConfig>(() => {
        return THEME_CONFIGS[currentTheme.value] || THEME_CONFIGS[DEFAULT_THEME]
    })

    // 计算属性：所有可用主题
    const availableThemes = computed(() => {
        return Object.entries(THEME_CONFIGS).map(([key, config]) => ({
            key: key as ThemeKey,
            ...config
        }))
    })

    // 计算属性：是否为深色主题
    const isDarkTheme = computed(() => {
        const darkThemes: ThemeKey[] = ['cyber', 'neon', 'ocean', 'sunset', 'forest', 'galaxy', 'dark']
        return darkThemes.includes(currentTheme.value)
    })

    // 切换主题
    const switchTheme = async (themeKey: ThemeKey) => {
        if (themeKey === currentTheme.value) return

        // 开始切换动画
        isTransitioning.value = true

        try {
            // 设置新主题
            setCurrentTheme(themeKey)

            // 触发触觉反馈
            try {
                uni.vibrateShort()
            } catch (error) {
                console.warn('触觉反馈不可用:', error)
            }

            // 显示切换提示
            uni.showToast({
                title: `已切换到${THEME_CONFIGS[themeKey].name}`,
                icon: 'none',
                duration: 1500
            })

            // 应用主题到DOM
            applyThemeToDOM(THEME_CONFIGS[themeKey])

            // 延迟结束动画状态
            setTimeout(() => {
                isTransitioning.value = false
            }, 300)
        } catch (error) {
            console.error('主题切换失败:', error)
            isTransitioning.value = false
        }
    }

    // 应用主题到DOM（仅 H5 有效，其他端通过内联 style 变量生效）
    const applyThemeToDOM = (themeConfig: ThemeConfig) => {
        // 非 H5 平台没有 document，直接跳过，避免产生控制台警告
        // #ifndef H5
        return
        // #endif

        try {
            // #ifdef H5
            const root = document.documentElement || document.body
            if (root && (root as any).style) {
                root.style.setProperty('--theme-primary', themeConfig.primary)
                root.style.setProperty('--theme-secondary', themeConfig.secondary)
                root.style.setProperty('--theme-accent', themeConfig.accent)
                root.style.setProperty('--theme-gradient', themeConfig.gradient)
                root.style.setProperty('--theme-background', themeConfig.background)
                root.style.setProperty('--theme-surface', themeConfig.surface)
                root.style.setProperty('--theme-text-primary', themeConfig.text.primary)
                root.style.setProperty('--theme-text-secondary', themeConfig.text.secondary)
                root.style.setProperty('--theme-text-tertiary', themeConfig.text.tertiary)
                root.style.setProperty('--theme-border', themeConfig.border)
                root.style.setProperty('--theme-shadow', themeConfig.shadow)

                // 设置主题类名
                root.className = (root.className || '').replace(/theme-\w+/g, '')
                root.classList.add(`theme-${currentTheme.value}`)
            }
            // #endif
        } catch (error) {
            // 避免在非 H5 平台产生噪音日志
        }
    }

    // 获取主题配置
    const getThemeConfig = (themeKey?: ThemeKey): ThemeConfig => {
        return THEME_CONFIGS[themeKey || currentTheme.value] || THEME_CONFIGS[DEFAULT_THEME]
    }

    // 重置主题
    const resetTheme = () => {
        switchTheme(DEFAULT_THEME)
    }

    // 初始化主题
    const initTheme = () => {
        // 应用当前主题到DOM
        applyThemeToDOM(currentThemeConfig.value)
    }

    // 监听主题变化，自动应用到DOM
    watch(
        currentTheme,
        (newTheme) => {
            applyThemeToDOM(THEME_CONFIGS[newTheme])
        },
        { immediate: false }
    )

    return {
        // 状态
        currentTheme: readonly(currentTheme),
        isTransitioning: readonly(isTransitioning),

        // 计算属性
        currentThemeConfig,
        availableThemes,
        isDarkTheme,

        // 方法
        switchTheme,
        getThemeConfig,
        resetTheme,
        initTheme
    }
})

// 导出类型
export type ThemeStore = ReturnType<typeof useThemeStore>
